const { Sequelize, Model, Op } = require('sequelize')
const { sequelize } = require('../../core/db');
const { Art } = require('./art')
const { LikeError, DisLikeError, NotFound } = require('../../core/http-exception')

// 业务表 用户 收藏 中间表  记录 收藏的 期刊  期刊类型
class Favor extends Model {
    // 点赞 喜欢 
    static async like(art_id, type, uid) {
        // 数据库事务 保证  多个表的数据的一致性

        const favor = await Favor.findOne({
            where: {
                art_id,
                type,
                uid
            }
        })
        if (favor) {
            throw new LikeError();
        }
        // 根据 type  添加实体的 fav_nums 数量+1
        return sequelize.transaction(async t => {
            await Favor.create({
                art_id,
                type,
                uid
            }, { transaction: t })

            const art = await Art.getData(art_id, type, false)
            await art.increment('fav_nums', {
                by: 1,
                transaction: t
            })

        })
    }

    // 取消点赞  
    static async disLike(art_id, type, uid) {
        // 数据库事务 保证  多个表的数据的一致性

        const favor = await Favor.findOne({
            where: {
                art_id,
                type,
                uid
            }
        })
        if (!favor) {
            throw new DisLikeError();
        }
        // 根据 type  添加实体的 fav_nums 数量+1
        return sequelize.transaction(async t => {
            // 用当前查出的 对象
            await favor.destroy({
                force: true, // 是否是软 删除
                transaction: t
            })

            const art = await Art.getData(art_id, type, false)
            await art.decrement('fav_nums', {
                by: 1,
                transaction: t
            })

        })
    }

    // 用户是否点击过 当前期刊
    static async userLikeIt(art_id, type, uid) {
        // favor 中是否存在数据
        const favor = await Favor.findOne({
            where: {
                art_id,
                type,
                uid
            }
        })

        return favor ? true : false;

    }

    // 获取 我喜换
    static async getMyClassicFavors(uid) {
        const art = await Favor.findAll({
            uid,
            type: {
                [Op.not]: 400 // 排除书籍
            }
        })

        if (!art) {
             throw new NotFound()
        }

        return await Art.getList(art)
    }


}
Favor.init({
    uid: Sequelize.INTEGER,
    art_id: Sequelize.INTEGER,
    type: Sequelize.INTEGER
}, {
    sequelize,
    tableName: 'favor'
})

module.exports = {
    Favor
}